package com.mind.customer.handler.zhenghua;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.mind.common.enums.DataType;
import com.mind.common.utils.file.vo.FileVo;
import com.mind.customer.api.ocr.OCRUtils;
import com.mind.customer.exception.AjObjectNotFoundException;
import com.mind.customer.handler.common.CommonHandler;
import com.mind.system.domain.AjObject;
import com.mind.system.domain.AjTicketTask;
import com.mind.system.domain.vo.Field;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
public class ZhengHuaStampHandler {
    @Resource
    private CommonHandler commonHandler;
    private String stampKey = "SIGNATURE_STAMP";

    @Resource
    private OCRUtils ocrUtils;


    public JSONObject handler(String ticketType, String cate, String name, FileVo fileVo, AjTicketTask task) throws AjObjectNotFoundException, IOException {
        AjObject ajObject = commonHandler.getObject( ticketType, cate, name);
        List<Field> fields = JSONArray.parseArray(ajObject.getFields(), Field.class);
        if(isEnableStamp(fields)){
            JSONArray stampResult = handleStamp(ocrUtils.getStamp(fileVo, task));
            if(stampResult.size()>0){
                return new JSONObject(){{
                    put(stampKey, stampResult);
                }};
            }
        }
        return null;
    }

    public boolean isEnableStamp(List<Field> fields){
        for (Field field: fields){
            return Arrays.asList(field.getAttachmentDataField().split(",")).contains( stampKey) && DataType.ROW.getCode().equals(field.getDataType());
        }
        return false;
    }

    private JSONArray handleStamp(JSONObject stamp) {
        JSONArray stampResult = new JSONArray();
        if (stamp.containsKey("resultStamps")) {
            JSONArray stampArray = stamp.getJSONArray("resultStamps");
            for (int i = 0; i < stampArray.size(); i++) {
                JSONObject r = stampArray.getJSONObject(i);
                r.put("resultSigFlag", stamp.getIntValue("resultSigFlag") != -1 ? "是" : "否");
                stampResult.add(r);
            }
        }
        return stampResult;
    }
}
